<template>
    <div class="app-container">
      <projectHeader @tabClick="tabClick"></projectHeader>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <el-form-item label="规则名称" prop="name">
           <el-input
             v-model="queryParams.name"
             placeholder="请输入规则名称"
             clearable
             style="width: 240px"
             @keyup.enter="handleQuery"
           />
         </el-form-item>
         <!-- <el-form-item label="平台类型" prop="platformType">
           <el-select
               v-model="queryParams.platformType"
               placeholder="请选择平台类型"
               clearable
               style="width: 240px"
           >
             <el-option
                 v-for="dict in dict.type.rule_platform_type"
                 :key="dict.value"
                 :label="dict.label"
                 :value="dict.value"
             />
           </el-select>
         </el-form-item> -->
         <el-form-item label="规则类型" prop="type">
           <el-select
               v-model="queryParams.type"
               placeholder="请选择规则类型"
               clearable
               style="width: 240px"
           >
             <el-option
                 v-for="dict in dict.type.rule_type"
                 :key="dict.value"
                 :label="dict.label"
                 :value="dict.value"
             />
           </el-select>
         </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:eaFeeRule:add']"
          >新增
          </el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:billing_rule:remove']"
          >删除
          </el-button>
        </el-col> -->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 表格数据 -->
      <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="名称" prop="name" :show-overflow-tooltip="true"/>
          <el-table-column label="平台类型 " align="center" prop="platformType">
            <template slot-scope="{row}">
              <dict-tag :options="dict.type.rule_platform_type" :value="row.platformType" />
            </template>
          </el-table-column>
          <el-table-column label="计费规则类型" align="center" prop="type">
            <template slot-scope="{row}">
              <dict-tag :options="dict.type.rule_type" :value="row.type" />
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="{row}">
              <el-button
               type="text"
               icon="el-icon-edit"
               @click="handleUpdate(row)"
               v-hasPermi="['system:eaFeeRule:edit']"></el-button>
              <el-button
               type="text"
               icon="el-icon-delete"
               @click="handleDelete(row)"
               v-hasPermi="['system:eaFeeRule:remove']"></el-button>
            </template>
          </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改计费规则对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="规则名称" prop="name" style="width: 100%;">
            <el-input v-model="form.name" placeholder="请输入规则名称"/>
          </el-form-item>
          <el-form-item label="运营商" prop="operatorId" style="width: 100%;" v-if="!userInfo.operatorId">
            <el-select
                v-model="form.operatorId"
                placeholder="请选择运营商"
                clearable
                style="width: 240px"
                :disabled="form.id ? true : false"
            >
              <el-option
                  v-for="item in operatorList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="规则类型" prop="type" style="width: 100%;">
            <el-select
                v-model="form.type"
                placeholder="请选择规则类型"
                clearable
                style="width: 240px"
            >
              <el-option
                  v-for="dict in typeList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="Number(dict.value)"
              />
            </el-select>
          </el-form-item>
          <div v-if="form.type == 4">
            <div class="diaolg_title flex_hcneter">
              <div class="title1">尖峰平谷规则</div>
            </div>
            <el-tabs v-model="activeName">
              <el-tab-pane label="基本配置" name="first">
                <el-row>
                  <el-col :span="12" v-for="(item,index) in countyLvList" :key="index">
                    <el-form-item :label="item.label" :prop="item.prop">
                      <el-input-number v-model="form[item.prop]" :precision="2" :step="0.1" :min="0"></el-input-number>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-tab-pane>
              <el-tab-pane label="时间计价规则" name="second">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="时间段" label-width="90px" label-position="left">价格(元/Kwh)</el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="批量修改选中" label-width="120px" label-position="left">
                      <el-select v-model="selectValue" @change="xuanzhong" class="m-2" placeholder="请选择" >
                        <el-option v-for="item in dict.type.rule_price_type"
                        :key="item.value"
                        :value="Number(item.value)"
                        :label="item.label" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <div  >
                    <el-col :span="12" v-for="(rule, index) in form.stateGridElectric.intervalPrice" :key="index" style="margin-bottom: 10px;">
                      <div  style="width: 100%;" class="flex_hcneter">
                        <el-checkbox v-model="rule.checked">
                          <div class="flex_hcneter" style="margin-right: 10px;font-weight: 700;">{{ rule.startTime + '-' + rule.endTime}}</div>
                        </el-checkbox>
                        <el-select v-model="rule.type" class="m-2" placeholder="请选择" >
                          <el-option v-for="item in dict.type.rule_price_type"
                          :key="item.value"
                          :value="Number(item.value)"
                          :label="item.label" />
                        </el-select>
                      </div>

                    </el-col>
                  </div>

                </el-row>
              </el-tab-pane>
            </el-tabs>

          </div>
          <div v-if="form.type == 3">
            <div class="diaolg_title flex_hcneter">
              <div class="title1">电量规则</div>
            </div>
            <el-row v-for="(item,index) in form.electrics " :key="index">
              <el-col :span="12">
                <el-form-item label="电费" prop="electricityPrice" style="width: 100%;">
                  <el-input-number v-model="item.electricityPrice" :precision="2" :step="0.1" :min="0"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="服务费" prop="servicePrice" style="width: 100%;">
                  <el-input-number v-model="item.servicePrice" :precision="2" :step="0.1" :min="0"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="时间段" style="width: 100%;" >
                  <div style="width: 100%;display: flex;align-items: center;">
                    <el-time-select
                      key="time1"
                      style="width: 160px;"
                      placeholder="开始时间"
                      v-model="item.startTime"
                      :picker-options="{
                        start: '00:00',
                        step: '00:30',
                        end: '24:00'
                      }">
                    </el-time-select>
                    <div style="margin: 0 5px;">-</div>
                    <el-time-select
                    style="width: 160px;"
                    key="time2"
                    placeholder="结束时间"
                    v-model="item.endTime"
                    :picker-options="{
                      start: '00:00',
                      step: '00:30',
                      end: '24:00'
                    }">
                    </el-time-select>
                    <div style="margin-left: 10px;">
                      <el-button size="small" @click="addList(3)" type="primary">+</el-button>
                      <el-button size="small" v-if="form.electrics.length > 1" @click="delList(index,3)" type="primary">-</el-button>
                    </div>
                  </div>
                </el-form-item>
              </el-col>

            </el-row>
          </div>
          <div v-if="form.type == 2">
            <div class="diaolg_title flex_hcneter">
              <div class="title1">功率规则</div>
            </div>
            <el-row v-for="(item,index) in form.powers " :key="index">
              <el-col :span="12">
                <el-form-item label="最小功率" prop="minPower" style="width: 100%;">
                  <el-input-number v-model="item.minPower" :precision="2" :step="0.1" :min="0" :max="item.maxPower"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="最大功率" prop="maxPower" style="width: 100%;">
                  <el-input-number v-model="item.maxPower" :precision="2" :step="0.1" :min="item.minPower"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="价格" prop="price	" style="width: 100%;">
                  <div style="width: 100%;display: flex;">
                    <el-input-number v-model="item.price" :precision="2" :step="0.1" :min="0"></el-input-number>
                    <div style="margin-left: 5px;">元</div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="时间" prop="time" style="width: 100%;">
                  <div style="width: 100%;display: flex;">
                    <el-input-number v-model="item.time"  :step="1" step-strictly :min="1"></el-input-number>
                    <div style="margin-left: 5px;">小时</div>
                    <div style="margin-left: 10px;">
                      <el-button size="small" @click="addList(2)" type="primary">+</el-button>
                      <el-button size="small" v-if="form.powers.length > 1" @click="delList(index,2)" type="primary">-</el-button>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div v-if="form.type == 1">
            <div class="diaolg_title flex_hcneter">
              <div class="title1">时间规则</div>
            </div>
            <el-row v-for="(item,index) in form.times " :key="index">
              <el-col :span="12">
                <el-form-item label="价格" prop="price	" style="width: 100%;">
                  <div style="width: 100%;display: flex;">
                    <el-input-number v-model="item.price" :precision="2" :step="0.1" :min="0"></el-input-number>
                    <div style="margin-left: 5px;">元</div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="时间" prop="time" style="width: 100%;">
                  <div style="width: 100%;display: flex;">
                    <el-input-number v-model="item.time"  :step="1" step-strictly :min="1"></el-input-number>
                    <div style="margin-left: 5px;">小时</div>
                    <div style="margin-left: 10px;">
                      <el-button size="small" @click="addList(1)" type="primary">+</el-button>
                      <el-button size="small" v-if="form.times.length > 1" @click="delList(index,1)" type="primary">-</el-button>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div  v-if="form.type == 2 || form.type == 3 || form.type == 4">
            <div class="diaolg_title flex_hcneter">
              <div class="title1">前端展示</div>
            </div>
            <el-row v-for="(item,index) in form.views" :key="index">
              <el-col :span="24">
                <el-form-item label="展示数值" prop="value" style="width: 100%;">
                  <div style="width: 100%;display: flex;">
                    <el-input-number v-model="item.value" :precision="2" :step="0.1" :min="0"></el-input-number>
                    <div style="margin-left: 5px;">{{form.type == 2 ? '小时' : '元'}}</div>
                    <div style="margin-left: 10px;">
                      <el-button size="small" @click="addList(0)" type="primary">+</el-button>
                      <el-button size="small" v-if="form.views.length > 1" @click="delList(index,0)" type="primary">-</el-button>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
import * as api from "@/api/station/eaFeeRule";
import { eaOperatSelect } from "@/api/station/operator";
export default {
  name: "EaFeeRule",
  dicts: ['rule_platform_type','rule_type','rule_price_type'],
  components: {  },
  data() {
    return {
      activeName:'first',
      intervalPrice:[],
      countyLvList:[
        {label:'尖电费',prop:'sharpElectricityPrice',},{label:'尖服务费',prop:'sharpServicePrice',},
        {label:'峰电费',prop:'peakElectricityPrice',},{label:'峰服务费',prop:'peakServicePrice',},
        {label:'平电费',prop:'flatElectricityPrice',},{label:'平服务费',prop:'flatServicePrice',},
        {label:'谷电费',prop:'valleyElectricityPrice',},{label:'谷服务费',prop:'valleyServicePrice',},
      ],
      form: {},// 表单参数
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      queryParams: {// 查询参数
        pageNum: 1,
        pageSize: 10,
      },
      // 总条数
      total: 0,
      rules: {
        name: [{required: true, message: "规则名称不能为空", trigger: "blur"}],
        platformType: [{required: true, message: "请选择平台类型", trigger: "change"}],
        type: [{required: true, message: "请选择规则类型", trigger: "change"}],
        operatorId: [{required: true, message: "请选择运营商", trigger: "change"}],
        sharpElectricityPrice: [{required: true, message: "尖电费不能为空", trigger: "blur"}],
        sharpServicePrice: [{required: true, message: "尖服务费不能为空", trigger: "blur"}],
        peakElectricityPrice: [{required: true, message: "峰电费不能为空", trigger: "blur"}],
        peakServicePrice: [{required: true, message: "峰服务费不能为空", trigger: "blur"}],
        flatElectricityPrice: [{required: true, message: "平电费不能为空", trigger: "blur"}],
        flatServicePrice: [{required: true, message: "平服务费不能为空", trigger: "blur"}],
        valleyElectricityPrice: [{required: true, message: "谷电费不能为空", trigger: "blur"}],
        valleyServicePrice: [{required: true, message: "谷服务费不能为空", trigger: "blur"}],
      },
      operatorOptions:[],//所属运营商
      list:[],//页面数据
      eltypeList:[
        {label:'按时间',value:1},
        {label:'按功率',value:2},
      ],//二轮类型数据
      sltypeList:[
        {label:'按电量',value:3},
        {label:'尖峰平谷规则',value:4},
      ],//四轮类型数据
      typeList:[],//类型数据
      plateform:{},//选择的平台项目
      operatorList:[],//运营商数据
      userInfo:{},//用户信息
      timePriceRuleOptions:[//价格(元/Kwh)
        {value: 0, label: '尖费率'},
        {value: 1, label: '峰费率'},
        {value: 2, label: '平费率'},
        {value: 3, label: '谷费率'},
      ],
      selectValue:'',
    };
  },
  created() {
    this.inittime()
    let user = this.$store.state.user || {}
    this.userInfo = user.userInfo || {}
  },
  methods: {
    xuanzhong(){//国量批量修改
      let form = {...this.form}
      form.stateGridElectric.intervalPrice.forEach(item=>{
        if(item.checked) item.type = this.selectValue
      })
      this.form = {...form}
    },
    inittime(){//初始化国家点亮数据
      let num = 30
      let startstart = 0
      let startend = 0
      let endstart = 0
      let endend = 0
      this.intervalPrice = []
      for (var i = 0;i<48;i++) {
        startstart = i * num
        startend = i * num
        endstart = i * num
        endend = (i + 1) * num
        if(startend >= 60) {
          let beishu = parseInt(startend / 60)
          startstart = beishu
          startend = startend - beishu * 60
        }
        if(endend >= 60) {
          let beishu1 = parseInt(endend / 60)
          endstart = beishu1
          endend = endend - beishu1 * 60
        }
        if(i>0) {
          let endTime = this.intervalPrice[i-1].endTime
          let sendTime = endTime.split(':')
          startstart = sendTime[0]
          startend = sendTime[1]
        }
        this.intervalPrice.push(
        {startTime:(startstart < 10 ? '0' + Number(startstart) : startstart) +  ':' + (startend < 10 ? '0' + Number(startend) : startend),
        endTime:(endstart < 10 ? '0' + Number(endstart) : endstart) +  ':' + (endend < 10 ? '0' + Number(endend) : endend),type:2,checked:false,
        })
      }
      console.log('this.intervalPrice',this.intervalPrice)
    },
    async eaOperatSelect(){//运营商选择列表
      let res = await eaOperatSelect({platformType:this.plateform.value})
      this.operatorList = res.data
    },
    tabClick(e){//平台切换
      this.plateform = {...e}
      if(e.value == 2) {
        this.typeList = [...this.eltypeList]
      }else{
        this.typeList = [...this.sltypeList]
      }
      this.queryParams.pageNum = 1
      this.getList()
    },
    addList(type){//列表添加
      if(type == 3){
        this.form.electrics.push({})
      }else if(type == 2) {
        this.form.powers.push({})
      }else if(type == 1) {
        this.form.times.push({})
      }else{
        this.form.views.push({})
      }
    },
    delList(index,type){//列表删除
      if(type == 3){
        this.form.electrics.splice(index,1)
      }else if(type == 2) {
        this.form.powers.splice(index,1)
      }else if(type == 1) {
        this.form.times.splice(index,1)
      }else{
        this.form.views.splice(index,1)
      }
    },
    plateChange(e){//平台类型改变
      let form = {...this.form}
      form.type = ''
      if(e == 2) {
        this.typeList = [...this.eltypeList]
      }else{
        this.typeList = [...this.sltypeList]
      }
      this.form = {...form}
    },
    getList() {
      this.loading = true;
      this.queryParams.platformType = this.plateform.value
      api.listEaFeeRule(this.queryParams).then(response => {
        this.list = response.rows || [];
        this.total = response.total || 0;
        this.loading = false;
      });
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.open = true;
      this.reset();
      this.title = "添加收费规则";
      this.eaOperatSelect()
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.open = true;
      this.title = "修改收费规则";
      api.getEaFeeRule(id).then(response => {
        let data = response.data || {}
        this.plateChange(data.platformType)
        let electrics = data.electrics || [{}]
        if(electrics[electrics.length-1].endTime == '00:00') electrics[electrics.length-1].endTime = '24:00'
        let powers = data.powers || []
        let times = data.times || []
        let views = data.views || []
        let stateGridElectric = data.stateGridElectric || null
        if(stateGridElectric) {
          this.countyLvList.map(item=>{
            data[item.prop] = stateGridElectric[item.prop]
          })
        }
        this.form = {
          ...data,
          electrics:electrics,
          powers:powers.length ? powers : [{}],
          times:times.length ? times : [{}],
          views:views.length ? views : [{}],
          stateGridElectric : stateGridElectric ? stateGridElectric : {intervalPrice:[...this.intervalPrice],},
        };
        this.eaOperatSelect()
      });
    },
    // 表单重置
    reset() {
      this.form = {
        electrics:[{}],
        powers:[{}],
        times:[{}],
        views:[{}],
        stateGridElectric:{intervalPrice:[...this.intervalPrice],},
        platformType:this.plateform.value,
      };
      this.activeName = 'first'
      this.resetForm("formRef");
    },
    isNull(str){
    	return str === undefined || str === null || str === ''
    },
    timeBijiao(time1,time2){
    	if(!time1 || !time2) return false
    	let time1List = time1.split(':')
    	let time2List = time2.split(':')
    	return (Number(time1List[0]) > Number(time2List[0])) || ( time1List[0] == time2List[0] &&  Number(time1List[1]) > Number(time2List[1]) )
    },
    submitForm() {
      this.$refs["formRef"].validate(valid => {
        if (valid) {
          let type = this.form.type
          let electrics = [...this.form.electrics] || []
          let powers = [...this.form.powers] || []
          let times = [...this.form.times] || []
          let views = [...this.form.views] || []
          let flag = ''
          if(type == 3) {
            if(electrics[electrics.length-1].endTime == '00:00') electrics[electrics.length-1].endTime = '24:00'
            electrics.map((item,index)=>{
              if(this.isNull(item.electricityPrice) || this.isNull(item.endTime) || this.isNull(item.servicePrice)
              || this.isNull(item.startTime)){
                 flag = '请填写完整电费规则'
              }else if(
                index > 0 && index < (electrics.length - 1)
                && (this.timeBijiao(electrics[index-1].endTime,electrics[index].startTime)
                || this.timeBijiao(electrics[index].endTime,electrics[index + 1].startTime)
              ) ){
                flag = '电费规则请填写正确的时间段'
              }else if( this.timeBijiao(electrics[index].startTime,electrics[index].endTime) ) {
                flag = '电费规则请填写正确的时间段'
              }
            })
          }
          if(type == 2) {
            powers.map(item=>{
              if(this.isNull(item.maxPower) || this.isNull(item.minPower) || this.isNull(item.price)
              || this.isNull(item.time)) flag = '请填写完整功率规则'
            })
          }
          if(type == 1) {
            times.map(item=>{
              if(this.isNull(item.time) || this.isNull(item.price)) flag = '请填写完整时间规则'
            })
          }
          if( (type == 2 || type == 3 || type == 4) && !flag) {
            views = views.map(item=>{
              if(this.isNull(item.value) ) flag = '请填写完整前端展示'
              return {
                ...item,
                unit: type == 2 ? '小时' : '元'
              }
            })
          }
          if(flag) return this.$modal.msgError(flag)
          let form = {
            ...this.form,
            electrics:type == 3 ? electrics : [],
            powers:type == 2 ? powers : [],
            times:type == 1 ? times : [],
            views:type == 2 || type == 3 || type == 4 ? views : [],
            stateGridElectric: type == 4 ? {
              ...this.form.stateGridElectric,
            } : null
          }
          if(type == 4) {
            this.countyLvList.map(item=>{
              form.stateGridElectric[item.prop] = this.form[item.prop]
            })
          }
          if (this.form.id != undefined) {
            if(this.userInfo.operatorId) delete form.operatorId
            api.updateEaFeeRule(form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false;
              this.getList();
            });
          } else {
            api.addEaFeeRule(form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    handleDelete(row) {//删除
      const del_ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + del_ids + '"的数据项？').then(function() {
        return api.delEaFeeRule(del_ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
  }
};
</script>
<style lang="scss">
  .diaolg_title{
    .title1{font-size: 20px;font-weight: bold;margin-bottom: 15px;}
  }

</style>
